package com.hm.oltu.api;

import javax.servlet.http.HttpServletRequest;

import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.hm.common.su.bean.ServerResponse;
import com.hm.common.util.CommonUtil;
import com.hm.oltu.def.CommonDef.OperationStatus;
import com.hm.oltu.def.OauthDef.Api;
import com.hm.oltu.model.User;
import com.hm.oltu.service.OAuthService;
import com.hm.oltu.service.UserService;
import com.hm.oltu.su.ServerResponseResult;
import com.hm.oltu.vo.UserVo;

/**
 * @author shishun.wang
 * @date 2016年12月6日 下午5:27:35
 * @version 1.0
 * @describe
 */
@RestController
@RequestMapping(Api.UserApi.USER_FINFO)
public class UserInfoController {

	@Autowired
	private OAuthService oAuthService;

	@Autowired
	private UserService userService;

	// public @ResponseBody ResponseEntity<ControllerResult<UserVo>>
	// getUserInfo(HttpServletRequest request) {
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody ResponseEntity<ServerResponse<UserVo>> getUserInfo(HttpServletRequest request) {
		try {
			// 构建OAuth资源请求
			OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);
			// 获取Access Token
			String accessToken = oauthRequest.getAccessToken();
			if (CommonUtil.isEmpty(accessToken) || !oAuthService.checkAccessToken(accessToken)) {
				return ServerResponseResult.failed(OperationStatus.LOAD_FAIL + ",accessToken is failure");
			}
			String username = oAuthService.getUsernameByAccessToken(accessToken);
			User user = userService.findByUsername(username);
			if (CommonUtil.isEmpty(user)) {
				return ServerResponseResult.failed(OperationStatus.LOAD_FAIL + ",user is not found ");
			}

			UserVo userVo = new UserVo();
			BeanUtils.copyProperties(user, userVo);
			return ServerResponseResult.success(userVo);
		} catch (Exception e) {
			return ServerResponseResult.failed(e);
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<ServerResponse<String>> registerUserInfo(
			@RequestBody(required = true) UserVo userVo) {
		try {
			if (CommonUtil.isNotEmpty(userService.findByUsername(userVo.getUsername()))) {
				return ServerResponseResult.failed("当前用户已存在,注册失败");
			}
			return ServerResponseResult.success(userService.createUser(userVo).getId());
		} catch (Exception e) {
			return ServerResponseResult.failed(e);
		}
	}
}
